package epoch.game.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	
	//建立连接超时
	private static final int CONNECT_TIME_OUT=3000;
	//从连接池获取连接超时
	private static final int CONNECT_REQUEST_TIME_OUT=1000;
	//socket超时，读取数据超时
	private static final int SOCKET_TIME_OUT=2000;
	
	/**
	 * 执行http get请求
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static String wget(String url) throws IOException{
		// 执行get访问
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpGet httpGet = new HttpGet(url);
			RequestConfig reqConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIME_OUT).setConnectionRequestTimeout(CONNECT_REQUEST_TIME_OUT)
					.setSocketTimeout(SOCKET_TIME_OUT).build();
			httpGet.setConfig(reqConfig);
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("wget failed! Unexpected response status: " + status);
					}
				}

			};
			String responseBody = httpclient.execute(httpGet, responseHandler);
			return responseBody;
		} finally {
			httpclient.close();
		}
	}
		
	/**
	 * 执行post请求
	 * @param url 请求url
	 * @param params 请求参数
	 * @return
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String,String> params) throws IOException {
		return doPost(url, params, "utf-8");
	}
	
	/**
	 * 执行post请求
	 * @param url
	 * @param params
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String,String> params, String charset) throws IOException {
		// 执行get访问
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			RequestConfig reqConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIME_OUT).setConnectionRequestTimeout(CONNECT_REQUEST_TIME_OUT)
					.setSocketTimeout(SOCKET_TIME_OUT).build();
			httpPost.setConfig(reqConfig);
			// 设置参数
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
					list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				httpPost.setEntity(entity);
			}
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("doPost failed! Unexpected response status: " + status);
					}
				}

			};
			String responseBody = httpclient.execute(httpPost, responseHandler);
			return responseBody;
		} finally {
			httpclient.close();
		}
	}
}
